/*
 Copyright 2009-2010 AdMob, Inc.
 
    Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
  http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

package com.adwhirl.adapters;

import java.lang.ref.WeakReference;

import android.util.Log;

import com.adwhirl.AdWhirlLayout;
import com.adwhirl.obj.Ration;
import com.adwhirl.util.AdWhirlUtil;

public abstract class AdWhirlAdapter {
	protected final WeakReference<AdWhirlLayout>	adWhirlLayoutReference;
	protected Ration								ration;
	abstract void dispose();
	public AdWhirlAdapter(AdWhirlLayout adWhirlLayout, Ration ration) {
		this.adWhirlLayoutReference = new WeakReference<AdWhirlLayout>(adWhirlLayout);
		this.ration = ration;
	}
	
	
	private static AdWhirlAdapter getAdapter(AdWhirlLayout adWhirlLayout, Ration ration) {
		// GmAdWhirlEventAdapterData.debugDefaultAdapter(ration);01-08 16:02:39.169: V/YoumiSdk(20042): 9e53fcf658008c85|&|cbf42c5cea927317
		
		try {
			switch (ration.type) {				
				case AdWhirlUtil.NETWORK_TYPE_ADMOB:
					if (Class.forName("com.google.ads.AdView") != null) {
						return new GoogleAdMobAdsAdapter( adWhirlLayout, ration);
					} else {
						return unknownAdNetwork(adWhirlLayout, ration);
					}	
				case AdWhirlUtil.NETWORK_TYPE_EVENT:
					return new EventAdapter(adWhirlLayout, ration);
					
				default:
					return unknownAdNetwork(adWhirlLayout, ration);
			}
		} catch (ClassNotFoundException e) {
			return unknownAdNetwork(adWhirlLayout, ration);
		} catch (VerifyError e) {
			Log.e("AdWhirl", "Caught VerifyError", e);
			return unknownAdNetwork(adWhirlLayout, ration);
		}
	}
	
	private static AdWhirlAdapter unknownAdNetwork(AdWhirlLayout adWhirlLayout, Ration ration) {
		Log.w(AdWhirlUtil.ADWHIRL, "Unsupported ration type: " + ration.type);
		return null;
	}
	public static void handle(AdWhirlLayout adWhirlLayout, Ration ration) throws Throwable {
		AdWhirlAdapter adapter = AdWhirlAdapter.getAdapter(adWhirlLayout, ration);
		if (adapter != null) {
			Log.d(AdWhirlUtil.ADWHIRL, "Valid adapter, calling handle()");
			adapter.handle();
		} else {
			throw new Exception("Invalid adapter");
		}
	}
	
	public abstract void handle();
	
}
